package io.geekidea.boot.system.dto;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Data
@Slf4j
public class QuickDto {
    private List<Map<String, Object>> rowsDiff;

    public static <T> List<T> convert(List<Map<String, Object>> rowsDiff, Class<T> targetClass) {
        List<T> list = new ArrayList<>();
        if (rowsDiff == null) {
            log.error("快速修改转化类，需要包含id字段， target= {}", targetClass.getName());
            return list;
        }
        rowsDiff.forEach(map -> {
            try {
                T t = targetClass.getConstructor().newInstance();
                Field id = ReflectionUtils.findField(targetClass, "id");
                if (id == null) {
                    log.error("快速修改转化类，需要包含id字段， target= {}", targetClass.getName());
                    return;
                }
                ReflectionUtils.makeAccessible(id);
                ReflectionUtils.setField(id, t, Long.parseLong((String) map.get("id")));

                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    if (Objects.equals("id", entry.getKey())) {
                        continue;
                    }
                    Field field = ReflectionUtils.findField(targetClass, entry.getKey());
                    if (field == null) {
                        log.error("快速修改转化类，需要包含{}字段， target= {}", entry.getKey(), targetClass.getName());
                        continue;
                    }
                    ReflectionUtils.makeAccessible(field);
                    ReflectionUtils.setField(field, t, entry.getValue());
                }
                list.add(t);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return list;
    }
}
